
from bin.alipan import YxhpyAliPan
import time
from flask import Flask, render_template
from config.config import SYNC_DELAY, ALI_FOLDER_NAME, LOCAL_FOLDER_NAME
from threading import Thread
from datetime import timedelta

app = Flask(__name__)
# 自动重载模板文件
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True

# 设置静态文件缓存过期时间
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)


def main():
    ali_pan = YxhpyAliPan()
    file_id = ali_pan.get_file_id(ALI_FOLDER_NAME)
    while True:
        start_time = time.time()
        start_info = "同步开始，请勿在同步的时候删除文件"
        print(start_info)
        ali_pan.info.append(start_info)
        ali_pan.remove_sync()
        ali_pan.sync_path(LOCAL_FOLDER_NAME, file_id)
        wait_info = f"同步完成，等待{SYNC_DELAY}秒"
        print(wait_info)
        ali_pan.info.append(wait_info)
        time.sleep(SYNC_DELAY)
        print("同步耗时：", (time.time() - start_time))


@app.route("/")
def index():
    data = {"ALI_FOLDER_NAME": ALI_FOLDER_NAME,
            "LOCAL_FOLDER_NAME": LOCAL_FOLDER_NAME,
            "info": YxhpyAliPan.info[-3:],
            "log": YxhpyAliPan.info}
    return render_template("index.html", **data)


def start_web():
    app.run("0.0.0.0", 8081)


if __name__ == '__main__':
    t = Thread(target=start_web)
    t.start()
    main()
